<template>
  <div class="fillcontain" >
    <bt-col-header title="接口案例"></bt-col-header>
    <div class="page-content">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px"
              class="form-container">
        <el-row>
          <el-col :span="12">
            <el-form-item label="案例编码" prop="caseCode">
              <el-input v-model="dataForm.caseCode" disabled  placeholder="案例编码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="案例名称" prop="caseName">
              <el-input v-model="dataForm.caseName"  placeholder="案例名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属场景" prop="sceneIdentify">
              <el-select v-model="dataForm.sceneIdentify"  :disabled="isEdit" filterable placeholder="请选择">
                <el-option
                  v-for="item in scenes"
                  :key="item.sceneIdentify"
                  :label="item.sceneName"
                  :value="item.sceneIdentify">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否有效"  prop="isEffect">
              <el-switch
                v-model="dataForm.isEffect"
                active-color="#13ce66"
                inactive-color="#ff4949"
                on-value="1" on-text="是" off-text="否" off-value="0">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>

          <el-col :span="12">
            <el-form-item label="请求模板" prop="reqTemplateCode">
              <el-select v-model="dataForm.reqTemplateCode"  :disabled="isEdit" filterable placeholder="请选择">
                <el-option
                  v-for="item in reqTemplates"
                  :key="item.templateCode"
                  :label="item.label"
                  :value="item.templateCode"
                @click.native="changeReqTemplate(item)">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="返回模板" prop="resTemplateCode">
              <el-select v-model="dataForm.resTemplateCode"  :disabled="isEdit" filterable placeholder="请选择">
                <el-option
                  v-for="item in resTemplates"
                  :key="item.templateCode"
                  :label="item.label"
                  :value="item.templateCode"
                  @click.native="changeResTemplate(item)">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注"  >
              <el-input type="textarea" :rows="3" v-model="dataForm.remark" placeholder="备注"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    
      <div class="contain-padding">
        <el-tabs type="border-card" >
          <el-tab-pane label="请求报文">
            <!-- <el-tree
              :data="reqTreeList"
              node-key="id"
              :expand-on-click-node="false"> -->
              <div class="border-card-node">
                <span class="custom-tree-node" v-for="data in reqTreeList" :key="data.id">
                    <span>{{ data.itemName }}</span>
                    <span v-if="data.itemType==='List'">
                        <el-button type="text" v-if="data.isAdd !='1'" size="mini" @click="() => reqAppend(node,data)"> 添加 </el-button>
                        <el-button type="text" v-if="data.isAdd==='1'" size="mini" @click="() => reqRemove(node,data)"> 删除 </el-button>
                    </span>
                    <span v-else>
                        <el-input v-model="data.itemValue" :placeholder="data.itemName" ></el-input>
                    </span>
                  </span>
              </div>
                  
            <!-- </el-tree> -->
          </el-tab-pane>
          <el-tab-pane label="返回报文">
            <!-- <el-tree
              :data="resTreeList"
              node-key="id"
              :expand-on-click-node="false"> -->
              <div class="border-card-node">
                <span class="custom-tree-node" v-for="data in resTreeList" :key="data.id">
                    <span>{{ data.itemName }}</span>
                    <span v-if="data.itemType==='List'">
                        <el-button type="text" v-if="data.isAdd !='1'" size="mini" @click="() => resAppend(node,data)"> 添加 </el-button>
                        <el-button type="text" v-if="data.isAdd==='1'" size="mini" @click="() => resRemove(node,data)"> 删除 </el-button>
                    </span>
                    <span v-else>
                        <el-input v-model="data.itemValue" :placeholder="data.itemName" ></el-input>
                    </span>
                  </span>
              </div>
                  
            <!-- </el-tree> -->
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="content-footer">
        <el-button :plain="true" type="info" @click="dataFormSubmit()">确定</el-button>
        <el-button @click="toList">取消</el-button>
      </div>
    </div>
    
  </div>
</template>

<script>
    import { listScene } from '@/api/ruleConfig/scene'
    import { getTreeMessage,listTemplateData } from '@/api/testCase/interfaceTemplate'
    import { getData, saveData } from '@/api/testCase/interfaceCase'
    import constant from "../../../../../api/constant";

    export default {
        data () {
            return {
                reqTreeIndex: 1,
                resTreeIndex: 1,
                loading: false,
                isEdit: false,
                scenes: [],
                reqTemplates: [],
                resTemplates: [],
                dataList: [],
                reqArrayDataList: [], // 实体类一级 LIST
                resArrayDataList: [], // 所有list
                reqTreeList: [], // 所有list
                resTreeList: [], // 所有list
                visible: false,
                dataForm: {
                    id: null,
                    reqTemplateCode: '',
                    reqEntityId:null,
                    resEntityId:null,
                    resTemplateCode: '',
                    caseCode: '',
                    caseName: '',
                    sceneIdentify: '',
                    reqContent: '',
                    resContent: '',
                    remark: '',
                    isEffect: '1',
                    reqIndex: 1,
                    resIndex: 1
                },
                dataRule: {
                    // caseCode: [
                    //     {required: true, message: '案例编码不能为空', trigger: 'blur'}
                    // ],
                    caseName: [
                        {required: true, message: '案例名称不能为空', trigger: 'change'}
                    ],
                    sceneIdentify: [
                        {required: true, message: '所属场景不能为空', trigger: 'change'}
                    ],
                    reqTemplateCode: [
                        {required: true, message: '请求模板不能为空', trigger: 'blur'}
                    ],
                    resTemplateCode: [
                        {required: true, message: '返回模板不能为空', trigger: 'change'}
                    ]
                },
            }
        },
        created () {
          let id = this.$route.params.id
          this.init(id)
        },
        activated() {
          let id = this.$route.params.id
          this.init(id)
        },
        methods: {
            toList(){
                constant.clearTag(this)
                this.$router.push({name: constant.routerName.listInterfaceCase})
            },
            reqRemove (node, data) {
                if (this.dataForm.reqEntityId === data.entityId) {
                    const index = node.parent.data.findIndex(d => d.id === data.id)
                    node.parent.data.splice(index, 1)
                } else {
                    const index = node.parent.data.children.findIndex(d => d.id === data.id)
                    node.parent.data.children.splice(index, 1)
                }
            },
            reqAppend (node, data) {
                let newData = null
                this.reqArrayDataList.forEach(item => {
                    if (item.itemId === data.itemId) {
                        newData = JSON.parse(JSON.stringify(item))
                        this.dataForm.reqIndex = this.dataForm.reqIndex + 1
                        newData.id = this.dataForm.reqIndex
                        newData.isAdd = '1' // 代表新增的
                    }
                })
                if (this.dataForm.reqEntityId === data.entityId) {
                    node.parent.data.push(newData)
                } else {
                    node.parent.data.children.push(newData)
                }
            },
            resRemove (node, data) {
                if (this.dataForm.resEntityId === data.entityId) {
                    const index = node.parent.data.findIndex(d => d.id === data.id)
                    node.parent.data.splice(index, 1)
                } else {
                    const index = node.parent.data.children.findIndex(d => d.id === data.id)
                    node.parent.data.children.splice(index, 1)
                }
            },
            resAppend (node, data) {
                let newData = null
                this.resArrayDataList.forEach(item => {
                    if (item.itemId === data.itemId) {
                        newData = JSON.parse(JSON.stringify(item))
                        this.dataForm.resIndex = this.dataForm.resIndex + 1
                        newData.id = this.dataForm.resIndex
                        newData.isAdd = '1' // 代表新增的
                    }
                })
                if (this.dataForm.resEntityId === data.entityId) {
                    node.parent.data.push(newData)
                } else {
                    node.parent.data.children.push(newData)
                }
            },


            changeReqTemplate (item) {
                this.dataForm.reqEntityId = item.entityId
                let params = {
                    templateCode: this.dataForm.reqTemplateCode,
                    messageType: '1'
                }

                getTreeMessage(params).then(res => {
                    this.dataForm.reqIndex = res.data.data.treeIndex
                    this.reqTreeList = res.data.data.treeList
                    this.reqArrayDataList = res.data.data.allArrayList // 所有列表
                })
            },
            changeResTemplate (item) {
                this.dataForm.resEntityId = item.entityId
                let params = {
                    templateCode: this.dataForm.resTemplateCode,
                    messageType: '2'
                }

                getTreeMessage(params).then(res => {
                    this.dataForm.resIndex = res.data.data.treeIndex
                    this.resTreeList = res.data.data.treeList
                    this.resArrayDataList = res.data.data.allArrayList // 所有列表
                })
            },
            // 获取场景信息
            async listInterfaceData () {
                let params = {
                    is_effect:'1'
                }
                await listScene(params).then(res => {
                    this.scenes = res.data.data
                })
                return this.scenes
            },
            // 获取场景信息
            async listTemplateData (type) {
                let params = {
                    is_effect:'1',
                    template_type:type
                }
                let template = []
                await listTemplateData(params).then(res => {
                    // template = res.data.data
                    if(res.data.data){
                        res.data.data.forEach(item=>{
                            item['label'] = item.templateCode+'-'+item.templateName
                            template.push(item)
                        })
                    }
                })
                return template
            },
            async init (id) {
                this.visible = true

                this.isEdit = false
                this.reqTreeList = []

                this.reqArrayDataList = []
                this.resTreeList = []
                this.resArrayDataList = []
                this.$store.dispatch('loading/CHANGE_LOADING', true)
                this.scenes = await this.listInterfaceData()
                this.reqTemplates = await this.listTemplateData('1')
                this.resTemplates = await this.listTemplateData('2')
                this.$nextTick(() => {

                    this.$refs['dataForm'].resetFields()
                    if (id && id != "undefined") {
                        this.dataForm.id = id
                        this.isEdit = true
                        let params = {
                            id: this.dataForm.id + ''
                        }
                        getData(params).then(res => {
                            if (res.data.data && res.data.resultCode === 0) {
                                this.$store.dispatch('loading/CHANGE_LOADING', false)
                                this.dataForm = res.data.data.msg;
                                this.reqTreeList = res.data.data.reqTreeList
                                this.resTreeList = res.data.data.resTreeList

                                this.reqArrayDataList = res.data.data.reqAllArrayList // 所有列表
                                this.resArrayDataList = res.data.data.resAllArrayList // 所有列表

                                this.dataForm.reqEntityId = res.data.data.reqTemplate.entityId
                                this.dataForm.resEntityId = res.data.data.resTemplate.entityId
                            }
                        }).catch(err=>{
                            this.$store.dispatch('loading/CHANGE_LOADING', false)
                        })
                    }else{
                        this.$store.dispatch('loading/CHANGE_LOADING', false)
                    }
                })
            },

            // 表单提交
            dataFormSubmit () {
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                        let params = {
                            reqArrayList: JSON.stringify(this.reqTreeList),
                            resArrayList: JSON.stringify(this.resTreeList),
                            dataForm: JSON.stringify(this.dataForm)
                        }
                        this.$store.dispatch('loading/CHANGE_LOADING', true)
                        saveData(params).then(res => {
                            this.$store.dispatch('loading/CHANGE_LOADING', false)
                            if (res.data && res.data.resultCode === 0) {
                                this.$message({
                                    message: '操作成功',
                                    type: 'success',
                                    duration: 1500,
                                    onClose: () => {
                                        this.visible = false
                                        this.dataForm = {
                                            id: null,
                                            entityId: null,
                                            interfaceId: null,
                                            interfaceIdentify: '',
                                            interfaceName: '',
                                            messageName: '',
                                            reqContent: '',
                                            resContent: '',
                                            remark: '',
                                            isEffect: '1',
                                            reqIndex: 1,
                                            resIndex: 1
                                        }
                                        // this.$emit('refreshDataList')
                                        this.toList()
                                    }
                                })
                            } else {
                                this.$message.error(res.data.resultMsg)
                            }
                        }).catch(err=>{
                            this.$store.dispatch('loading/CHANGE_LOADING', false)
                        })
                    }
                })

            }
        }
    }
</script>

<style lang="scss">
  .el-tabs--border-card .el-tabs__content{
    padding: 0 !important;
  }
  .el-table__row .el-form-item__content{
    margin-left: 0 !important;
  }
  .el-table__row .el-form-item{
    margin-bottom: 0 !important;
  }
  .el-tree-node{
    padding:10px;
    background: #fff;
  }
  .border-card-node {
    padding: 10px 10px 0 10px;
    .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;
      padding-bottom: 10px;
    }  
  }
  
</style>
